import os.path
import time

from fastapi import APIRouter
from pydantic import BaseModel
from starlette.background import  BackgroundTasks

import dao
from utils.id_generate import createNameByTime
from utils.parse_url import parse_url
from ytdlp_download import download_file,get_video_path
from fastapi.responses import FileResponse



class JobParams(BaseModel):
    url: str


router = APIRouter()

@router.post("/start_job")
async def start_job(background_tasks: BackgroundTasks,params: JobParams):
    url = parse_url(params.url)

    if url is None:
        return {
            "code":500,
            "message":f"{params.url}不能解析到有效地址"
        }
    by_url = dao.VideoDaoInstance.getVideoByUrlAndStatus(url,1,2)
    if by_url is not None:
        tip = "已经下载成功" if by_url["status"] == 2 else "正在下载"
        return {
            "code": 500,
            "message": f"{url}:{tip}"
        }


    name = createNameByTime()
    background_tasks.add_task(download_file, url, name)

    return {
        "url":url,
        "code":200,
        "name":name
    }

@router.get("/get_jobs")
async def get_jobs(status:int = 0):
    list = dao.VideoDaoInstance.getVideoListByStatus(status)
    return {
        "code":200,
        "data":list
    }

@router.get("/delete_job")
async def delete_job(id:int):
    dao.VideoDaoInstance.deleteVideoById(id)
    return {
        "code": 200,
        "data": id
    }

@router.get("/download_video/{name}")
async def download_video(name:str):
    videoPath = os.path.join(get_video_path(), name + ".mp4")
    if not os.path.exists(videoPath):
        return {
            "code":500,
            "message": f"{videoPath} 不存在"
        }
    return FileResponse(
        path=videoPath,
        filename=name+".mp4",  # 自定义下载时的文件名
        media_type="video/mp4"
    )


def mock_task(url, id):
    print("mock_task start")
    print(f"url: {url}, id: {id}")
    time.sleep(5)
    print("mock_task end")

